package com.qkl.user.validation;

import com.qkl.user.annotation.EqualFields;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.lang.reflect.Field;

public class EqualFieldsValidator implements ConstraintValidator<EqualFields, Object> {
    // 第一个字段名
    private String firstField;
    // 第二个字段名
    private String secondField;

    // 初始化：获取注解中的字段名
    @Override
    public void initialize(EqualFields constraintAnnotation) {
        this.firstField = constraintAnnotation.first();
        this.secondField = constraintAnnotation.second();
    }

    // 验证逻辑：比较两个字段的值是否相等
    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        try {
            // 通过反射获取两个字段的值
            Field first = value.getClass().getDeclaredField(firstField);
            Field second = value.getClass().getDeclaredField(secondField);

            // 允许访问私有字段
            first.setAccessible(true);
            second.setAccessible(true);

            // 获取字段值
            Object firstValue = first.get(value);
            Object secondValue = second.get(value);

            // 两个值都为 null 时视为相等；否则比较实际值
            if (firstValue == null && secondValue == null) {
                return true;
            }
            return firstValue != null && firstValue.equals(secondValue);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            // 反射获取字段失败（通常是字段名错误）
            throw new RuntimeException("字段验证失败：" + e.getMessage());
        }
    }
}
